<?php
/**
 * Created by PhpStorm.
 * User: xieky
 * Date: 2018/1/11
 * Time: 12:32
 */

namespace common\services\myhtsq;

use common\entities\myhtsq\ContractManageEntity;
use common\repositories\myhtsq\ContractApplicationRepository;
use common\repositories\myhtsq\ErpUserRepository;
use common\support\Helper;
use Yii;
use common\services\BaseService;
use common\repositories\myhtsq\ContractManageRepository;
use common\repositories\myhtsq\ContractCompanyRepository;
use common\entities\ConfigEntity;

class OutStorageService extends BaseService
{
    private $_erpinterface;
    //以下产品不经多租户授权,需过滤
    static $noNeedProducts = [
        '938ed790-4b63-465a-9eef-3e88c010e3d7',
        'bd3c0d01-fa7f-4ca8-a493-9b3b5c8d8ddb',
        '2c914692-3a81-4969-9630-c5fa946540cb',
        '2f24ad79-4bca-42ef-a275-5adb74adfd90',
        '2fd5ae7b-889b-409d-8893-9bae7ddc1e7d',
        '605fc722-0a73-4578-b74f-b2436fd9367e',
        '70883d11-7f63-46f4-a2b6-16f94d3132fe',
        '8da7bb48-c64f-436e-a67f-4ea1c06bc7aa'];
    public function __construct($config=[],ErpInterfaceService $erpservice)
    {
        $this->_erpinterface = $erpservice;
        parent::__construct($config);
    }

    /**
     *读取出库列表
     */
    public function GetDeliveryList($curpage=1,$pagesize = 20,$keyword = '',$datatype = '',$datastatus = ''){
        $erpinterface = new ErpInterfaceService();
        $result = $erpinterface->GetDeliveryList($curpage,$pagesize,$keyword,$datatype,$datastatus);
        foreach($result['data']->rows as $item){
            $item->delivery_status_name = $this->getDeliveryStatusName($item->delivery_status);
            if(!empty($item->signguid)){
                $signguids = explode(',',substr($item->signguid,0,-1));
                $record = ContractManageRepository::getContractsCodeByLinkErpId($signguids);
                if(!empty($record)){
                    $item->stock_contract_info = $record;
                }else{
                    $item->stock_contract_info = [];
                }
            }else{
                $item->stock_contract_info = [];
            }
        }
        return $result;
    }

    /**
     *读取出库名字
     */
    public function GetDeliveryDetail($deliveryGuid){
        $erpinterface = new ErpInterfaceService();
        $result = $erpinterface->GetDeliveryDetail($deliveryGuid);
        return $result;
    }

    /**
     *更新出库状态
     */
    public function UpdateDeliveryState($deliveryGuid,$status){
        $erpinterface = new ErpInterfaceService();
        $result = $erpinterface->UpdateDeliveryState($deliveryGuid,$status);
        return $result;
    }

    /**
     * 添加操作记录
     */
    public function AddOpreationRecord($deliveryGuid,$action,$remarks=''){
        $params = [
            'delivery_guid'=>$deliveryGuid,
            'action'=>$action,
            'action_user_id'=>Yii::$app->user->getIdentity()->userguid,
            'action_user'=>Yii::$app->user->getIdentity()->username,
            'remarks'=>$remarks
        ];
        $erpinterface = new ErpInterfaceService();
        $result = $erpinterface->AddOpreationRecord($params);
        return $result;
    }

    /**
     * 获取工作流流程
     */
    public function GetWorkflowProcessList($deliveryGuid){
        $erpinterface = new ErpInterfaceService();
        $result = $erpinterface->GetWorkflowProcessList($deliveryGuid);
        return $result;
    }

    /**
     * 创建租户
     */
    public function AddTenant($deliveryGuid){
        $erpinterface = new ErpInterfaceService();
        $interfaceData = $erpinterface->GetDeliveryDetail($deliveryGuid);
        if($interfaceData['success'] === false){
            return $interfaceData;
        }
        $tenantsInfo = $interfaceData['data']->YlInfo->Yl_Tenant;
        $resultmsg = "";

        foreach($tenantsInfo as $tenant){
            $platcode = $this->getPlatFormCode($tenant->BaseInfo->appname);
            $CompanyName = $tenant->BaseInfo->Enterprise_Name;
            $companycode = $tenant->BaseInfo->Enterprise_Code;
            if($platcode == 'mycaigou'){
                //获取云采购公司信息
                if(empty($CompanyName)){
                    return $this->getReturnResult([], false, '企业名称不允许为空!');
                }
                $cgparams = $erpinterface->GetCaigouParam($CompanyName);
                if($cgparams['success'] === false){
                    return $this->getReturnResult([], false, $cgparams['errmsg']);
                }
                $companycode = $cgparams['data'][0]->developerId;
                $domain = $cgparams['data'][0]->domain;
            }
            $params = [
                'platform_code'=>$platcode,
                'company_name'=>$CompanyName,
                'company_code'=>$companycode,
                'project_manager'=>$tenant->BaseInfo->Adviser_Name,
                'admin_mobile'=>$tenant->BaseInfo->Adviser_Tel,
                'admin_email'=>$tenant->BaseInfo->Adviser_Mail
            ];

            if(!empty($domain)){
                $params['company_domain'] = $domain;
            }

            $result = $erpinterface->AddTenant($params);
            if($result['success'] === true){
                $resultmsg = $resultmsg." ".$tenant->BaseInfo->Enterprise_Name."开通成功开通";
            }
        }
        if(empty($result)){
            if(empty($resultmsg)) {
                return $this->getReturnResult([], false, '没有租户信息!');
            }else{
                return $this->getReturnResult([], true, $resultmsg);
            }
        }
        if(empty($resultmsg)){
            return $result;
        }else {
            return $this->getReturnResult([], true, $resultmsg);
        }
    }

    /**
     * 租户授权
     */
    public function AuthTenant($deliveryGuid){
        $erpinterface = new ErpInterfaceService();
        $interfaceData = $erpinterface->GetDeliveryDetail($deliveryGuid);
        if($interfaceData['success'] === false){
            return $interfaceData;
        }
        $tenantsInfo = $interfaceData['data']->YlInfo->Yl_Tenant;
        $deliveryForm = $interfaceData['data']->DeliveryForm;
        $specialRemark = $interfaceData['data']->YlInfo->Remark;
        if(empty($tenantsInfo)){
            return $this->getReturnResult([],false,'没有租户信息!');
        }
        $msginfo = '授权成功';
        $isAllSuccess = true;

        foreach($tenantsInfo as $tenant) {
            $res = $this->getAuthParams($deliveryGuid,$tenant,$deliveryForm,$specialRemark);
            $tenantCode = $tenant->BaseInfo->Enterprise_Code;

            $successTenantCodeArr = Yii::$app->cache->get('auth_tenant-'.$deliveryGuid);
            $successTenantCodeArr = !empty($successTenantCodeArr) ? $successTenantCodeArr : [];

            if (!empty($successTenantCodeArr) && in_array($tenantCode, $successTenantCodeArr)) {
                continue;
            }

            if($res['success']){
                $params = $res['data'];
                $msginfo = $res['errmsg'];
                if(!empty($params)) {
                    $res = $this->_erpinterface->AuthTenant($params);
                    if ($res['success'] === false) {
                        $errresult = $res;

                        if (!empty($res['data']['success'])) {
                            //缓存失败的会签单号,下次单独提交
                            $fail_signno = [];
                            foreach ($res['data']['errMsg'] as $val) {
                                $fail_signno[] = $val['signature_number'];
                            }
                            Yii::$app->cache->set('auth-'.$deliveryGuid.'-'.$tenantCode, serialize($fail_signno));
                        }
                        //失败一个通通返回
                        return $errresult;
                    } else {
                        //对部分成功的合同进行清除
                        Yii::$app->cache->delete('auth-'.$deliveryGuid.'-'.$tenantCode);
                        //缓存成功的租户
                        $successTenantCodeArr = Yii::$app->cache->get('auth-'.$deliveryGuid);
                        $successTenantCodeArr = !empty($successTenantCodeArr) ? $successTenantCodeArr : [];
                        $successTenantCodeArr[] = $tenantCode;
                        Yii::$app->cache->set('auth_tenant-'.$deliveryGuid, $successTenantCodeArr);
                    }
                }else{
                    //$isAllSuccess = false;
                    //return $this->getReturnResult([],true,$res['errmsg']);
                }
            }else{
                $isAllSuccess = false;
                $errresult = $res;
            }
        }

        //对所有租户都成功的进行清除
        if ($isAllSuccess) {
            Yii::$app->cache->delete('auth_tenant-'.$deliveryGuid);
        }

        if(empty($errresult)){
            return $this->getReturnResult([],true,$msginfo);
        }
        return $errresult;
    }

    private function getAuthParams($deliveryGuid,$tenant,$deliveryForm,$specialRemark){
        $platform = $this->getPlatFormCode($tenant->BaseInfo->appname);

        $tenantCode = $tenant->BaseInfo->Enterprise_Code;
        $CompanyName = $tenant->BaseInfo->Enterprise_Name;
        //出库申请人邮箱
        $ErpUserRepository = new ErpUserRepository();
        $delivery_user_email = $ErpUserRepository->getUserEmailByGUID($deliveryForm->Person_Id);

        $tenantId = '';
        $linkerpid = '';
        $linkerpidArr = [];
        $isOneContract = true;
        $products = [];
        if($platform=='mycaigou'){
            $erpinterface = new ErpInterfaceService();
            $cgparams = $erpinterface->GetCaigouParam($CompanyName);
            if($cgparams['success'] === false){
                return $this->getReturnResult([], false, $cgparams['errmsg']);
            }
            //$tenantCode = $cgparams['data'][0]->developerId;
            $tenantCode = $cgparams['data'][0]->domain;
        }
        if(empty($platform) || empty($tenantCode)){
            return $this->getReturnResult([],false,'租户代码或平台代码不允许为空!');
        }

        $tenactinfos = $this->_erpinterface->GetTenantInfo($tenantCode,$platform);
        if($tenactinfos['success'] == false){
            return $tenactinfos;
        }

        if (!empty($tenactinfos['data'])) {
            foreach($tenactinfos['data'] as $info){
                if($info->platform_code == $platform){
                    $tenantId = $info->tenant_id;
                    break;
                }
            }
        }

        if(empty($tenantId)){
            return $this->getReturnResult([],false,'查询不到租户信息,无法授权!');
        }

        if (empty($tenant->Erp_Products)) {
            return $this->getReturnResult([],false,'无产品数据,无法授权!');
        }


        $existNoNeedProducts = false;

        foreach($tenant->Erp_Products as $product){
            /*if (empty($product->Signno)) {
                return $this->getReturnResult([],false,'会签单号为空,无法授权!');
                break;
            }*/
            //非特批出库会签单号不能为空
            if (empty($product->Signno) && $deliveryForm->Delivery_Scene!='4') {
                return $this->getReturnResult([],false,'会签单号为空,无法授权!');
                break;
            }
            //过滤不经多租户的产品
            if (in_array($product->Product_Info_Id, self::$noNeedProducts)) {
                $existNoNeedProducts = true;
                continue;
            }
            //$linkerpidArr[] = $product->Signguid;
            if (!empty($product->Signno)) {
                $linkerpidArr[$product->Signno] = $product->Signguid;
            }

            if(empty($linkerpid)){
                $linkerpid = $product->Signguid;
            }else{
                if($linkerpid != $product->Signguid){
                    $isOneContract = false;
                }
            }
            $contract = ContractManageRepository::getContractByErpContractId($product->Signguid);
            $max_num = ContractApplicationRepository::getMaxNumOfApp($contract['contract_id'],$product->Product_Info_Id);

            $delivery_max_num = $deliveryForm->Delivery_Scene=='4'?$product->Quantity:$product->Usernum;

            $p = [
                'product_id' => $product->Product_Info_Id,
                //'max_num' => $deliveryForm->Delivery_Scene=='4'?$product->Quantity:$product->Usernum,
                'max_num' => $max_num > $delivery_max_num? $max_num : $delivery_max_num,
                'auth_num' => $product->Quantity,
                'auth_period' => $product->Rent_Time
            ];
            if (!empty($product->Signno)) {
                $products[$product->Signno][] = $p;
            } else {
                //直属特批：无合同无会签 必须1对1
                $products[] = $p;
            }
        }

        //不经不租户的产品，过滤完如果为空，直接成功
        if ($existNoNeedProducts && empty($products)) {
            return $this->getReturnResult([],true,'授权成功');
        }

        $time = ConfigEntity::getDbNowDate();
        //失败的会签单号
        $fail_signno = Yii::$app->cache->get('auth-'.$deliveryGuid.'-'.$tenantCode);
        $fail_signno = !empty($fail_signno) ? unserialize($fail_signno) : [];

        $paramsArr = [];
        if($deliveryForm->Delivery_Scene!='4') {
            if (empty($linkerpid)) {
                return $this->getReturnResult([], false, '租户 ' . $tenantCode . ' 产品没有合同,无法授权!');
            }
            if (!$isOneContract) {
                //return $this->getReturnResult([], false, '目前授权只支持一个出库单一个租户有一个合同,租户 ' . $tenantCode . ' 有多个合同,无法授权!');
            }

            foreach ($linkerpidArr as $signno => $link) {
                //过滤已经成功会签单号-缓存的是未成功的会签单号
                if (!empty($fail_signno) && !in_array($signno, $fail_signno)) {
                    continue;
                }

                $contractInfo = ContractManageRepository::getContractInfoByLinkErpId($link);
                if (empty($contractInfo)) {
                    return $this->getReturnResult([], false, '查不到租户 ' . $tenantCode . ' 的合同信息,或者合同未审核,无法授权,请处理!');
                }
                $corpname = ContractCompanyRepository::getContractCompanyNameByCompanyId($contractInfo['company_id']);
                $summary = $corpname . ' ' . $contractInfo['sign_date'] . ' ' . $contractInfo['sign_amount'];
                $paramsArr[] = [
                    'stock_out_id' => $deliveryGuid,
                    'platform_code' => $platform,
                    'tenant_id' => $tenantId,
                    'contract_summary' => $summary,
                    'contract_summary_text' => empty($contractInfo['contract_remark'])?$summary:$contractInfo['contract_remark'],
                    'contract_code' => empty($contractInfo['contract_code'])?'':$contractInfo['contract_code'],
                    'contract_id' => empty($contractInfo['contract_id'])?'':$contractInfo['contract_id'],
                    'full_name' => empty($contractInfo['customer_full_name'])?$deliveryForm->Cst_Fullname:$contractInfo['customer_full_name'],
                    'corp_id' => empty($contractInfo['company_id'])?$deliveryForm->Cst_BuGUID:$contractInfo['company_id'],
                    'corp_name' => $corpname,
                    'account_time' => $time,
                    'sign_time' => empty($contractInfo['sign_date'])?null:$contractInfo['sign_date'],
                    'is_special_approval' => $deliveryForm->Delivery_Scene=='4'?'1':'0',
                    'special_approval_type' => $deliveryForm->Special_Type,
                    'special_approval_remark' => $specialRemark,
                    'special_approval_user_name' => $deliveryForm->Promise_Username,
                    'special_approval_user_id' => $deliveryForm->Promise_Userguid,
                    'promise_online' => $deliveryForm->Promise_Date,
                    'actual_online' => '',
                    'signature_number'  => $signno,//会签单号
                    'delivery_num' => $deliveryForm->Delivery_Code,//出库单号
                    'delivery_user_email' => $delivery_user_email,//出库申请人邮箱
                    'select_products' => $products[$signno]
                ];
            }
        }else{
            $corpname = $deliveryForm->Cst_BuName;
            $summary = $corpname;
            if (!empty($linkerpidArr)) {
                foreach ($linkerpidArr as $signno => $link) {
                    //过滤已经成功会签单号-缓存的是未成功的会签单号
                    if (!empty($fail_signno) && !in_array($signno, $fail_signno)) {
                        continue;
                    }
                    $contractInfo = ContractManageRepository::getContractInfoByLinkErpId($link);

                    if (!empty($contractInfo)) {
                        $corpname = ContractCompanyRepository::getContractCompanyNameByCompanyId($contractInfo['company_id']);
                        $summary = $corpname . ' ' . $contractInfo['sign_date'] . ' ' . $contractInfo['sign_amount'];
                    }
                    $paramsArr[] = [
                        'stock_out_id' => $deliveryGuid,
                        'platform_code' => $platform,
                        'tenant_id' => $tenantId,
                        'contract_summary' => $summary,
                        'contract_summary_text' => empty($contractInfo['contract_remark'])?$summary:$contractInfo['contract_remark'],
                        'contract_code' => empty($contractInfo['contract_code'])?'':$contractInfo['contract_code'],
                        'contract_id' => empty($contractInfo['contract_id'])?'':$contractInfo['contract_id'],
                        'full_name' => empty($contractInfo['customer_full_name'])?$deliveryForm->Cst_Fullname:$contractInfo['customer_full_name'],
                        'corp_id' => empty($contractInfo['company_id'])?$deliveryForm->Cst_BuGUID:$contractInfo['company_id'],
                        'corp_name' => $corpname,
                        'account_time' => $time,
                        'sign_time' => empty($contractInfo['sign_date'])?null:$contractInfo['sign_date'],
                        'is_special_approval' => $deliveryForm->Delivery_Scene=='4'?'1':'0',
                        'special_approval_type' => $deliveryForm->Special_Type,
                        'special_approval_remark' => $specialRemark,
                        'special_approval_user_name' => $deliveryForm->Promise_Username,
                        'special_approval_user_id' => $deliveryForm->Promise_Userguid,
                        'promise_online' => $deliveryForm->Promise_Date,
                        'signature_number'  => $signno,//会签单号
                        'delivery_num' => $deliveryForm->Delivery_Code,//出库单号
                        'delivery_user_email' => $delivery_user_email,//出库申请人邮箱
                        'select_products' => $products[$signno]
                    ];
                }
            } else {
                //直属特批：无合同无会签 必须1对1
                $paramsArr[] = [
                    'stock_out_id' => $deliveryGuid,
                    'platform_code' => $platform,
                    'tenant_id' => $tenantId,
                    'contract_summary' => $summary,
                    'contract_summary_text' => $summary,
                    'contract_code' => '',
                    'contract_id' => '',
                    'full_name' => $deliveryForm->Cst_Fullname,
                    'corp_id' => $deliveryForm->Cst_BuGUID,
                    'corp_name' => $corpname,
                    'account_time' => $time,
                    'sign_time' => null,
                    'is_special_approval' => $deliveryForm->Delivery_Scene=='4'?'1':'0',
                    'special_approval_type' => $deliveryForm->Special_Type,
                    'special_approval_remark' => $specialRemark,
                    'special_approval_user_name' => $deliveryForm->Promise_Username,
                    'special_approval_user_id' => $deliveryForm->Promise_Userguid,
                    'promise_online' => $deliveryForm->Promise_Date,
                    'actual_online' => '',
                    'signature_number'  => '',//会签单号
                    'delivery_num' => $deliveryForm->Delivery_Code,//出库单号
                    'delivery_user_email' => $delivery_user_email,//出库申请人邮箱
                    'select_products' => $products
                ];
            }
        }
        $paramsArrs['contract_list'] = $paramsArr;

        return $this->getReturnResult($paramsArrs,true,'授权成功');
    }

    private function getPlatFormCode($platformname){
        if(empty($platformname)){
            return '';
        }
        $platform = [
            '质量闭环服务系列' =>'yunfuwu',
            '采招外网-采购门户（企业版）租用服务' =>'czww',
            '采购在线服务系列' =>'mycaigou',
            '履约在线服务系列' =>'gcxt'
        ];
        return $platform[$platformname];
    }

    private function getDeliveryStatusName($code){
        $status = [
            '20' =>'审批',
            '21' =>'确认',
            '22' =>'开通',
            '23' =>'授权',
            '10'=>'打回',
            '24'=>'已上传接收单',
            '25'=>'已归档'
        ];

        if(empty($status[$code])){
            $name = $code;
        }else{
            $name = $status[$code];
        }
        return $name;
    }

    public function getReportList(){
        $res = $this->_erpinterface->getReportList();
        return $res;
    }

    public function getReportDetail($reportid){
        $res = $this->_erpinterface->getReportDetail($reportid);
        return $res;
    }
}